package cn.dlc.com.order.service.impl;

import cn.dlc.com.common.entity.Order;
import cn.dlc.com.common.entity.TxLog;
import cn.dlc.com.order.dao.OrderDao;
import cn.dlc.com.order.service.OrderService;
import cn.dlc.com.txlog.dao.TxLogDao;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.UUID;

/**
 * @author 邓立川
 * @date 2021/1/10 16:45
 * @desc 当前类的描述信息
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private TxLogDao txLogDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void createOrder(Order order) {

        // 创建一个回查的id
        String txId = UUID.randomUUID().toString();

        // 创建消息对象
        Message<String> message = MessageBuilder
                .withPayload(JSON.toJSONString(order))
                // 将这个用于回查的id塞进去
                .setHeader("txId",txId).build();

        // 发送半事务消息
        rocketMQTemplate.sendMessageInTransaction(
                "tx_producer_group",
                "tx_topic",
                message,order);
    }

    @Transactional
    @Override
    public void createOrderReal(Order order, String txId) {
        System.out.println("真正的执行创建订单的业务");
        // 保存订单
        orderDao.save(order);

        // 为了消息回查，弄一个这个东西
        TxLog txLog = new TxLog();
        txLog.setId(txId);
        txLog.setTxDate(new Date());
        txLogDao.save(txLog);

        // 模拟执行异常
        if("jack".equals(order.getOrderName())) {
            throw new RuntimeException("就是有异常啊....");
        }
    }
}
